//
//  XGL_LiveRoomChatView.swift
//  XGamesLive
//
//  Created by ios on 2024/5/30.
//

import UIKit

class XGL_LiveRoomChatView: UIView {
    
    var tableView: UITableView!
    var chatDatas: [PublishCommentData] = []

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.tableView = UITableView().then({ make in
            make.register(cellWithClass: XGL_LiveRoomChatTableViewCell.self)
            make.dataSource = self
            make.delegate = self
            make.backgroundColor = UIColor.clear
            make.rowHeight = UITableView.automaticDimension
            make.estimatedRowHeight = 150
            make.separatorStyle = .none
            make.showsVerticalScrollIndicator = false
        })
        self.addSubview(self.tableView)
        self.tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        self.snp.makeConstraints { make in
            make.height.equalTo(0)
        }
        
        tableView.addObserver(self, forKeyPath: "contentSize", options: [.new, .old, .prior], context: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        self.tableView.removeObserver(self, forKeyPath: "contentSize")
    }
}

extension XGL_LiveRoomChatView{
    @objc override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "contentSize" {
            // content size changed
            let height = self.tableView.contentSize.height > ScreenHeight * 0.4 ? ScreenHeight * 0.4 : self.tableView.contentSize.height
            self.snp.updateConstraints { (make) in
                make.height.equalTo(height > 0 ? (height) : 0 )
            }
        }
    }
}

extension XGL_LiveRoomChatView: UITableViewDelegate,UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.chatDatas.count
    }

 
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let model = self.chatDatas[indexPath.row]
        let cell = tableView.dequeueReusableCell(withClass: XGL_LiveRoomChatTableViewCell.self)
        cell.itemData = model
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
}
